package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.LoginResponseDTO;
import com.heima.model.media.dtos.WmUserLoginDto;
import com.heima.model.media.dtos.WmUserSaveDTO;
import com.heima.model.media.enums.WmUserTypeEnum;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.pojo.WmUser;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-03-22
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 保存自媒体用户
     *
     * @param dto
     * @return 自媒体用户id
     */
    @Override
    public Integer createWmUser(WmUserSaveDTO dto) {
        // 根据 ApUserId查询WmUser信息
        WmUser wmUserDB = this.getWmUserByApUserId(dto.getApUserId());
        // 如果查询到WmUser对象 则修改; 查询不到,则新增
        if (wmUserDB == null) {
            return this.buildWmUserAndInsert(dto);
        } else {
            return this.buildWmUserAndUpdate(dto, wmUserDB.getId());
        }

    }

    /**
     * 自媒体用户登录
     *
     * @param userLoginDto
     * @return
     */
    @Override
    public LoginResponseDTO<AdUserDto> login(WmUserLoginDto userLoginDto) {
        //  构造查询条件
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName, userLoginDto.getName());
        //  查询
        WmUser wmUser = this.getOne(queryWrapper);
        if (wmUser == null) {
            // 如果根据用户名查询不到用户，报错
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST.getCode(), "用户不存在");
        }
        // 使用BCryptPasswordEncoder提供的方法，比对密码
        boolean isMatches = encoder.matches(userLoginDto.getPassword(), wmUser.getPassword());
        if (!isMatches) {
            // 如果密码不匹配，报错
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 设置token和用户信息返回
        LoginResponseDTO<AdUserDto> loginResponseDTO = setTokenAndUser(wmUser);
        // 更新登陆时间
        this.updateLoginTimeById(wmUser.getId());
        return loginResponseDTO;
    }


    /**
     * 根据自媒体人用户id更新登陆时间
     *
     * @param id 媒体人用户id
     */
    private void updateLoginTimeById(Integer id) {
        WmUser wmUser = new WmUser();
        wmUser.setId(id);
        wmUser.setLoginTime(new Date());
        this.updateById(wmUser);
    }

    private LoginResponseDTO<AdUserDto> setTokenAndUser(WmUser wmUser) {
        LoginResponseDTO<AdUserDto> loginResponseDTO = new LoginResponseDTO<>();
        String token = JwtUtils.generateTokenExpireInSeconds(wmUser.getId(), 3600);
        loginResponseDTO.setToken(token);
        AdUserDto adUserDto = BeanHelper.copyProperties(wmUser, AdUserDto.class);
        loginResponseDTO.setUser(adUserDto);
        return loginResponseDTO;
    }

    /**
     * 构建WmUser对象并执行新增
     *
     * @param dto
     * @return wmUserId
     */
    private Integer buildWmUserAndInsert(WmUserSaveDTO dto) {
        WmUser wmUser = BeanHelper.copyProperties(dto, WmUser.class);
        wmUser.setType(WmUserTypeEnum.INDIVIDUAL.getCode());
        this.save(wmUser);
        return wmUser.getId();
    }


    /**
     * 构建WmUser对象并执行修改
     *
     * @param dto
     * @param wmUserId
     * @return wmUserId
     */
    private Integer buildWmUserAndUpdate(WmUserSaveDTO dto, Integer wmUserId) {
        WmUser wmUser = BeanHelper.copyProperties(dto, WmUser.class);
        wmUser.setId(wmUserId);
        wmUser.setType(WmUserTypeEnum.INDIVIDUAL.getCode());
        this.updateById(wmUser);
        return wmUserId;
    }

    /**
     * ApUserId查询WmUser信息
     *
     * @param apUserId
     * @return
     */
    private WmUser getWmUserByApUserId(Integer apUserId) {
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId, apUserId);
        return this.getOne(queryWrapper);
    }
}
